package superMarket;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;


public class Dao {
	private Connection connection;
	private PreparedStatement statement;
	private static Dao instance;
	public static Dao getInstance(){
		if(instance == null){
			instance = new Dao();
		}
		return instance;
	}
	public void open(){
		try{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			this.connection = DriverManager.getConnection("jdbc:mysql://localhost/supermarket", "root", "123456");
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	public void close(){
		try{
			this.connection.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	public Connection getConnection(){
		return connection;
	}
	public PreparedStatement getStatement(){
		return statement;
	}
//login account of customer
	public Customer loginCustomer(String id){
		Customer customer = null;
		this.open();
		try{
			String query = "SELECT * FROM Customer WHERE id = ?";
			this.statement = this.connection.prepareStatement(query);
			this.statement.setString(1, id);
			ResultSet set = this.statement.executeQuery();
			if(set.next()){
				customer = new Customer(set.getString("id"), set.getString("name"), set.getString("phone"), set.getDate("born"));
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		this.close();
		return customer;
	}
//add account of customer
	public boolean signupCustomer(String id, String name, String phone, Date born){
		boolean result = false;
		this.open();
		try{
			String query = "INSERT INTO Customer(id, name, phone, born) VALUE(?, ?, ?, ?)";
			this.statement = this.connection.prepareStatement(query);
			this.statement.setString(1, id);
			this.statement.setString(2, name);
			this.statement.setString(3, phone);
			this.statement.setDate(4, born);
			int receive = this.statement.executeUpdate();
			if(receive != -1){
				result = true;
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		this.close();
		return result;
	}
//login customer
	public void logoutCustomer(){
		this.close();
	}
	public static void main(String[] args) {
		Dao dao = Dao.getInstance();
		String strDate = "3/5/2012";
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
			java.util.Date date = sdf.parse(strDate);
			java.sql.Date sqlDate = new Date(date.getTime());
			System.out.println(dao.signupCustomer("aga12", "Kiều", "không nhớ", sqlDate));
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
}
